#include"HttpServer.hpp"

bool Echo(HttpRequest &req, HttpResponse *res)
{
    LOG(LogLevel::DEBUG)<<"------------Echo--------------";
    stringstream ss;
    //请求行
    ss<<req._method<<" "<<req._uri<<" "<<req._version<<"\r\n";

    //查询字符串
    for(auto  & e: req._params)
    {
        ss<<e.first<<"="<<e.second<<"\r\n";
    }

    //空行
    ss<<"\r\n";

    //请求头部
    for(auto  & e: req._headers)
    {
        ss<<e.first<<": "<<e.second<<"\r\n";
    }

    //空行
    ss<<"\r\n";

    //请求正文
    ss<<req._body;

    string data=ss.str();

    //填充响应
    res->SetBody(data,"tetx/plain");
    return true;
}

bool Post(HttpRequest &req, HttpResponse *res)
{
    //填充响应
    string data;
    Tool::ReadFile("./wwwroot/a.jpg",&data);
    res->SetBody(data,Tool::ExtMime("./wwwroot/a.jpg"));
    return true;
}
bool Put(HttpRequest &req, HttpResponse *res)
{
    //填充响应
    string data="222222222222222222222222222222222222222";

    //把请求正文写进文件里
    Tool::WriteFile("./wwwroot/bi.txt",req._body);

    res->SetBody(data,"tetx/plain");
    return true;
}
bool Delete(HttpRequest &req, HttpResponse *res)
{
    //填充响应
    string data="3333333333333333333333333333333333333";
    res->SetBody(data,"tetx/plain");
    return true;
}

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        cout<<"server serverport"<<endl;
        return 1;
    }
    SetValueLogLevel(LogLevel::DEADLY);
    
    HttpServer server(stoi(argv[1]),"./wwwroot",15);

    //设置从属Reactor线程个数
    server.SetReactorThreadCount(2);

    server.InsertGetHandles("/echo/",Echo);
    server.InsertPostHandles("/login/",Post);
    server.InsertPutHandles("/123/",Put);
    server.InsertDeleteHandles("/abc/",Delete);

    server.Start();
    return 0;
}
